<template>
  <div class="min-h-screen bg-gray-100">
    <Header />

    <div class="flex h-[calc(100vh-64px)]">
      <!-- 左侧导航 -->
      <div class="w-96 bg-white border-r border-gray-200 overflow-y-auto">
        <!-- 作品管理 -->
        <div class="p-4">
          <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold">我的作品</h3>
            <button
              @click="openBookCreateForm"
              class="px-2 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600"
            >
              新建
            </button>
          </div>
          <div class="space-y-2">
            <div
              v-for="book in books"
              :key="book.id"
              class="border rounded hover:bg-gray-50 transition-colors book-card"
            >
              <details class="cursor-pointer group">
                <summary
                  class="flex items-center p-2 focus:outline-none hover:bg-gray-100"
                >
                  <!-- 下拉箭头 -->
                  <span
                    class="mr-2 text-gray-600 transition-all duration-200 arrow-icon hover:text-gray-800"
                  >
                    <svg
                      width="16"
                      height="16"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                    >
                      <path
                        d="M9 18l6-6-6-6"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                      />
                    </svg>
                  </span>
                  <div class="flex-1 truncate">{{ book.name }}</div>
                  <div class="flex gap-2 ml-2 button-container">
                    <button
                      @click.stop="openBookEditForm(book.id)"
                      class="text-blue-500 hover:text-blue-700 text-sm px-2 py-1 rounded hover:bg-gray-200"
                    >
                      编辑
                    </button>
                    <button
                      @click.stop="deleteBook(book.id)"
                      class="text-red-500 hover:text-red-700 text-sm px-2 py-1 rounded hover:bg-gray-200"
                    >
                      删除
                    </button>
                  </div>
                </summary>

                <!-- 文章列表区域 -->
                <div class="pl-8 pr-2 pb-2 space-y-1">
                  <template v-if="book.articles?.length">
                    <div
                      v-for="article in book.articles"
                      :key="`${book.id}-${article.id}`"
                      class="p-2 text-sm hover:bg-gray-100 rounded cursor-pointer truncate relative article-item"
                    >
                      <div class="flex justify-between items-center">
                        <div @click="loadArticle(article)" class="flex-1">
                          <div class="font-medium">
                            {{ article.title || "未命名文章" }}
                          </div>
                          <div class="text-xs text-gray-400 mt-1">
                            创建于 {{ formatDate(article.create_time) }}
                          </div>
                        </div>
                        <button
                          @click.stop="deleteArticle(article)"
                          class="opacity-0 article-item:hover:opacity-100 text-red-500 hover:text-red-700 text-sm px-2 py-1 rounded hover:bg-gray-200 transition-opacity duration-200 delete-btn"
                        >
                          删除
                        </button>
                      </div>
                    </div>
                  </template>
                  <template v-else>
                    <div class="p-2 text-sm text-gray-400">暂无文章</div>
                  </template>

                  <button
                    @click.stop="createArticle(book)"
                    class="w-full text-center text-blue-500 hover:bg-blue-50 py-1 text-sm"
                  >
                    + 新建文章
                  </button>
                </div>
              </details>
            </div>
          </div>
        </div>
      </div>

      <!-- 主编辑区 -->
      <div class="flex-1 p-6 bg-gray-50">
        <input
          v-model="currentArticle.title"
          type="text"
          placeholder="请输入文章标题"
          class="w-full mb-6 p-4 text-2xl font-bold bg-white rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
        />

        <textarea
          v-model="currentArticle.content"
          placeholder="开始你的创作..."
          class="w-full h-full p-6 resize-none focus:outline-none text-gray-700 text-lg leading-relaxed"
        ></textarea>
      </div>

      <!-- 右侧AI侧边栏 -->
      <div class="w-96 bg-white border-l border-gray-200 overflow-y-auto">
        <div class="p-4 h-full flex flex-col">
          <div class="flex-1">
            <h3 class="text-lg font-semibold mb-4">AI助手</h3>

            <!-- AI续写区域 -->
            <div class="mb-6 space-y-4">
              <button
                @click="requestAI"
                :disabled="isContinuing"
                class="w-full px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 disabled:bg-gray-400 transition-colors"
              >
                {{ isContinuing ? "生成中..." : "AI续写" }}
              </button>

              <div v-if="aiGeneratedContent" class="bg-blue-50 rounded-lg p-4">
                <div class="text-gray-700 mb-2 generated-text">
                  {{ aiGeneratedContent }}
                </div>
                <button
                  @click="insertGeneratedContent"
                  class="w-full px-3 py-1.5 text-sm bg-white border border-blue-500 text-blue-500 rounded-md hover:bg-blue-50"
                >
                  插入到正文
                </button>
              </div>
            </div>

            <!-- 语法检查区域 -->
            <div class="mb-6 space-y-4">
              <button
                @click="requestGrammarCheck"
                :disabled="isChecking"
                class="w-full px-4 py-2 bg-purple-500 text-white rounded-md hover:bg-purple-600 disabled:bg-gray-400 transition-colors"
              >
                {{ isChecking ? "检查中..." : "语法检查" }}
              </button>

              <div
                v-if="grammarCheckResult"
                class="bg-purple-50 rounded-lg p-4"
              >
                <div class="text-gray-700 whitespace-pre-wrap">
                  {{ grammarCheckResult }}
                </div>
              </div>
            </div>
          </div>

          <div class="mt-auto pt-4 border-t">
            <button
              @click="submitArticle"
              class="w-full px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600 transition-colors"
            >
              提交文章
            </button>
          </div>
        </div>
      </div>

      <!-- 复用书籍表单组件 -->
      <BookForm
        v-model:visible="showBookForm"
        :is-edit="isBookEditMode"
        :book-id="currentBookId"
        @success="handleBookFormSuccess"
      />
    </div>
  </div>
</template>

<script>
import axios from "axios";
import showMessage from "@/utils/message.js";
import Header from "@/components/Header.vue";
import BookForm from "@/components/BookForm.vue";

export default {
  name: "WritingPage",
  components: { Header, BookForm },
  data() {
    return {
      aiGeneratedContent: "", // 专用于AI续写内容
      grammarCheckResult: "", // 专用于语法检查结果
      buffer: "",
      controller: null,
      isContinuing: false,
      isChecking: false,

      currentArticle: {
        id: null,
        title: "",
        content: "",
        book_id: null,
      },

      books: [],
      showBookForm: false,
      isBookEditMode: false,
      currentBookId: null,

      loading: {
        books: false,
        articles: false,
      },
    };
  },
  mounted() {
    this.fetchOwnedBooks();
  },
  methods: {
    async fetchOwnedBooks() {
      this.loading.books = true;
      try {
        const bookResponse = await axios.get("/api/owned/");

        const booksWithArticles = await Promise.all(
          bookResponse.data.map(async (book) => {
            try {
              // 获取带书籍过滤的文章
              const articlesRes = await axios.get(`/api/article/`, {
                params: { book: book.id }, // 显式传递过滤参数
              });

              // 强化数据校验
              const validArticles = (articlesRes.data || []).filter(
                (article) =>
                  article?.id && Number(article.book) === Number(book.id)
              );

              // 返回带完整结构的书籍对象
              return {
                ...book,
                articles: validArticles.map((article) => ({
                  ...article,
                  book_id: book.id, // 确保关联字段存在
                })),
              };
            } catch (error) {
              console.error(`书籍 ${book.id} 文章加载失败:`, error);
              return { ...book, articles: [] };
            }
          })
        );

        // 强制响应式更新
        this.books = booksWithArticles.filter(
          (book) => book && Array.isArray(book.articles)
        );
      } catch (error) {
        console.error("主数据获取失败:", error);
        showMessage("数据加载失败");
      }
      this.loading.books = false;
    },

    async requestGrammarCheck() {
      if (!this.currentArticle.content.trim()) {
        showMessage("请先输入一些内容");
        return;
      }

      this.isChecking = true;
      this.generatedContent = "";

      try {
        const response = await axios.post(
          "http://localhost:8001/api/ai-grammar-check/",
          { text: this.currentArticle.content }
        );

        // 直接处理完整响应
        if (response.data.errors?.length) {
          this.grammarCheckResult = response.data.errors
            .map(
              (error) => `原句：${error.sentence || "无"}
错误类型：${error.type}
错误内容："${error.content}"
建议修正："${error.suggestion}"`
            )
            .join("\n\n");
        } else {
          this.grammarCheckResult = "✓ 未发现明显语法错误";
        }
      } catch (error) {
        console.error("语法检查失败:", error);
        showMessage("语法检查服务异常");
      } finally {
        this.isChecking = false;
      }
    },

    createArticle(book) {
      this.currentArticle = {
        id: null,
        title: "新文章",
        content: "",
        book_id: book.id,
      };
    },

    async loadArticle(article) {
      try {
        const response = await axios.get(`/api/article/${article.id}/`);
        this.currentArticle = {
          id: article.id,
          title: response.data.title,
          content: response.data.content,
          book_id: response.data.book,
        };
      } catch (error) {
        console.error("加载文章失败:", error);
        showMessage("文章加载失败");
      }
    },

    async submitArticle() {
      try {
        if (!this.currentArticle.title.trim()) {
          showMessage("请填写文章标题");
          return;
        }

        const payload = {
          title: this.currentArticle.title,
          content: this.currentArticle.content,
          book: this.currentArticle.book_id,
        };

        if (this.currentArticle.id) {
          await axios.put(`/api/article/${this.currentArticle.id}/`, payload);
        } else {
          await axios.post("/api/article/", payload);
        }

        await this.fetchOwnedBooks();
        showMessage("保存成功！", "info");
      } catch (error) {
        console.error("保存失败:", error);
        showMessage("保存失败，请检查网络");
      }
    },

    openBookCreateForm() {
      this.isBookEditMode = false;
      this.currentBookId = null;
      this.showBookForm = true;
    },

    openBookEditForm(bookId) {
      this.isBookEditMode = true;
      this.currentBookId = bookId;
      this.showBookForm = true;
    },

    async deleteBook(bookId) {
      if (!confirm("确定要永久删除该作品吗？")) return;
      try {
        await axios.delete(`/api/book/${bookId}/`, {
          headers: { Authorization: "JWT " + localStorage.getItem("token") },
        });
        this.books = this.books.filter((book) => book.id !== bookId);
        showMessage("作品删除成功", "info");
      } catch (error) {
        console.error("删除失败:", error);
        showMessage("操作失败，请重试");
      }
    },

    async deleteArticle(article) {
      if (!confirm("确定要永久删除该文章吗？")) return;

      try {
        await axios.delete(`/api/article/${article.id}/`);

        // 从本地数据中移除
        this.books = this.books.map((book) => {
          if (book.id === article.book_id) {
            return {
              ...book,
              articles: book.articles.filter((a) => a.id !== article.id),
            };
          }
          return book;
        });

        // 如果删除的是当前正在编辑的文章
        if (this.currentArticle.id === article.id) {
          this.currentArticle = {
            id: null,
            title: "",
            content: "",
            book_id: null,
          };
        }

        showMessage("文章删除成功", "info");
      } catch (error) {
        console.error("删除失败:", error);
        showMessage("操作失败，请重试");
      }
    },

    handleBookFormSuccess() {
      this.fetchOwnedBooks();
    },

    async requestAI() {
      if (!this.currentArticle.content.trim()) {
        showMessage("请先输入一些内容");
        return;
      }

      this.isContinuing = true;
      this.aiGeneratedContent = "";
      this.buffer = "";

      try {
        const controller = new AbortController();
        this.controller = controller;

        const response = await fetch("http://localhost:8001/api/ai-continue/", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ text: this.currentArticle.content }),
          signal: controller.signal,
        });

        const reader = response.body.getReader();
        const decoder = new TextDecoder("utf-8");

        while (true) {
          const { done, value } = await reader.read();
          if (done) break;

          const chunk = decoder.decode(value, { stream: true });
          this.processChunk(chunk);
        }
      } catch (error) {
        if (error.name !== "AbortError") {
          console.error("请求失败:", error);
          showMessage("AI生成失败");
        }
      } finally {
        this.isContinuing = false;
        this.controller = null;
      }
    },

    processChunk(chunk) {
      this.buffer += chunk;
      const lines = this.buffer.split("\n");
      this.buffer = lines.pop();

      for (const line of lines) {
        const trimmed = line.trim();
        if (trimmed.startsWith("data: ")) {
          try {
            const data = JSON.parse(trimmed.slice(6));
            if (data.chunk !== "DONE") {
              this.aiGeneratedContent += data.chunk;
            }
          } catch (e) {
            console.warn("解析JSON失败:", trimmed.slice(6));
          }
        }
      }
    },

    insertGeneratedContent() {
      if (this.aiGeneratedContent) {
        this.currentArticle.content += this.aiGeneratedContent;
        this.aiGeneratedContent = "";
      }
    },

    beforeUnmount() {
      if (this.controller) {
        this.controller.abort();
      }
    },

    formatDate(dateString) {
      return new Date(dateString).toLocaleDateString();
    },
  },
};
</script>

<style>
/* 修复高度计算问题 */
.h-\[calc\(100vh-180px\)\] {
  height: calc(100vh - 180px);
}

/* 优化文本区域样式 */
textarea {
  min-height: 500px;
  line-height: 1.8;
  font-size: 18px;
  tab-size: 4;
}

/* 优化流式显示效果 */
.generated-text {
  white-space: pre-wrap;
  overflow-wrap: break-word;
  line-height: 1.8;
  animation: cursor 1s infinite;
}

@keyframes cursor {
  0% {
    border-right: 2px solid transparent;
  }
  50% {
    border-right: 2px solid #666;
  }
}

/* 增加流畅度 */
.ai-sidebar-content {
  max-height: 60vh;
  overflow-y: auto;
  scroll-behavior: smooth; /* 添加平滑滚动 */
}

.group:hover .book-actions {
  opacity: 1;
}

/* 展开时旋转 */
details[open] summary .arrow-icon {
  transform: rotate(90deg);
}

/* 文章列表最大高度 */
.book-articles {
  min-height: 50px;
  overflow-y: auto;
}

/* 隐藏按钮容器并添加过渡 */
.book-card .button-container {
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.2s ease;
}

/* 书籍悬停时显示按钮 */
.book-card:hover .button-container {
  opacity: 1;
  pointer-events: auto;
}

/* 文章删除按钮独立控制 */
.article-item:hover .delete-btn {
  opacity: 1;
  pointer-events: auto;
}

/* 为不同区域添加背景色区分 */
.bg-blue-50 {
  background-color: #eff6ff;
}

.bg-purple-50 {
  background-color: #f5f3ff;
}

/* 语法检查结果保持文本格式 */
.whitespace-pre-wrap {
  white-space: pre-wrap;
}
</style>
